using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Xliff.Ui.Domain;
using Xliff.Ui.Model;

namespace Xliff.Ui.Data
{
    public class TranslationUnitRepository
    {
        private readonly string _filePath;

        public TranslationUnitRepository(string filePath)
        {
            _filePath = filePath;
        }

        public IList<TranslationUnit> GetAll()
        {
            XDocument loaded = XDocument.Load(_filePath);

            return (from trans in loaded.Descendants("trans-unit")
                    select TranslationUnit.Create(
                        (int) trans.Attribute("id"),
                        trans.Element("target").Attribute("state").Value == "translated",
                        trans.Element("source").Value,
                        trans.Element("target").Value
                        )).ToList();
        }

        public IEnumerable<TranslationUnit> GetByCriteria(FilterCriteria criteria)
        {
            IList<TranslationUnit> result = GetAll();

            if (criteria.ShowUntranslated)
                result = (from t in result where !t.IsTranslated select t).ToList();

            if (!string.IsNullOrEmpty(criteria.Id))
            {
                int id = int.Parse(criteria.Id);
                result = (from t in result where t.Id.Equals(id) select t).ToList();
            }

            if (!string.IsNullOrEmpty(criteria.Original))
                result = (from t in result where t.Source.Contains(criteria.Original) select t).ToList();

            if (!string.IsNullOrEmpty(criteria.Translated))
                result = (from t in result where t.Target.Contains(criteria.Translated) select t).ToList();

            return result;
        }

        public void SaveChanges(IList<TranslationUnit> translations)
        {
            XDocument loaded = XDocument.Load(_filePath);

            foreach (TranslationUnit translation in translations)
            {
                if (translation.IsDirty)
                {
                    XElement transUnit =
                        loaded.Descendants("trans-unit").Where(x => x.Attribute("id").Value == translation.Id.ToString())
                            .Single();
                    transUnit.Element("target").SetAttributeValue("state",
                                                                  translation.IsTranslated
                                                                      ? "translated"
                                                                      : "needs-translation");
                    transUnit.Element("target").SetValue(translation.Target);

                    translation.MarkPersisted();
                }
            }

            File.Delete(_filePath);
            loaded.Save(_filePath);
        }
    }
}